﻿using UnityEngine;
using UnityEngine.UI;

public static class GlobalMusicValue
{
    public static float MusicValueG = 0;
}

public class VolumeSlider : MonoBehaviour
{
    public Slider volumeSlider;
    public AudioSource audioSource;

    // 单例模式实现
    private static VolumeSlider instance;
    public static VolumeSlider Instance { get { return instance; } }

    void Awake()
    {
        // 单例模式的标准实现
        if (instance != null && instance != this)
        {
            Destroy(this.gameObject);
            return;
        }
        else
        {
            instance = this;
        }

        // 确保 GameObject 不被销毁
        DontDestroyOnLoad(this.gameObject);
    }

    void Start()
    {
        if (volumeSlider != null)
        {
            volumeSlider.onValueChanged.AddListener(SetVolume);
            volumeSlider.value = PlayerPrefs.GetFloat("Volume", 1f);
            GlobalMusicValue.MusicValueG = volumeSlider.value;
        }

        if (audioSource == null)
        {
            audioSource = GetComponent<AudioSource>();
            if (audioSource == null)
            {
                Debug.LogError("AudioSource component not found.");
            }
            else
            {
                audioSource.volume = volumeSlider.value;
            }
        }
    }

    void SetVolume(float volume)
    {
        if (audioSource != null)
        {
            audioSource.volume = volume;
            GlobalMusicValue.MusicValueG = volume;
            PlayerPrefs.SetFloat("Volume", volume);
        }
    }
}